﻿using Rainbow_Game_Fans.Common;
using Rainbow_Game_Fans.Data;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.ApplicationModel.Resources;
using Windows.ApplicationModel.Store;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Graphics.Display;
using Windows.Storage;
using Windows.UI;
using Windows.UI.Core;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;
//using Windows.ApplicationModel;
//using Windows.ApplicationModel.Store;

// “中心应用程序”模板在 http://go.microsoft.com/fwlink/?LinkId=391641 上有介绍

namespace Rainbow_Game_Fans
{
    /// <summary>
    /// 显示分组的项集合的页。
    /// </summary>
    public sealed partial class HubPage : Page
    {
        private readonly NavigationHelper navigationHelper;
        private readonly ObservableDictionary defaultViewModel = new ObservableDictionary();
        //加载语言资源
        //private readonly ResourceLoader resourceLoader = ResourceLoader.GetForCurrentView("Resources");
        //加载设置
        ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
       
        public HubPage()
        {
            this.InitializeComponent();

            

            // 仅支持方向为纵向的中心
            DisplayInformation.AutoRotationPreferences = DisplayOrientations.Portrait;

            this.NavigationCacheMode = NavigationCacheMode.Required;

            this.navigationHelper = new NavigationHelper(this);
            this.navigationHelper.LoadState += this.NavigationHelper_LoadState;
            this.navigationHelper.SaveState += this.NavigationHelper_SaveState;
            
        }
      
        /// <summary>
        /// 获取与此 <see cref="Page"/> 关联的 <see cref="NavigationHelper"/>。
        /// </summary>
        public NavigationHelper NavigationHelper
        {
            get { return this.navigationHelper; }
        }

        /// <summary>
        /// 获取此 <see cref="Page"/> 的视图模型。
        /// 可将其更改为强类型视图模型。
        /// </summary>
        public ObservableDictionary DefaultViewModel
        {
            get { return this.defaultViewModel; }
        }

        /// <summary>
        /// 使用在导航过程中传递的内容填充页。  在从以前的会话
        /// 重新创建页时，也会提供任何已保存状态。
        /// </summary>
        /// <param name="sender">
        /// 事件的来源; 通常为 <see cref="NavigationHelper"/>
        /// </param>
        /// <param name="e">事件数据，其中既提供在最初请求此页时传递给
        /// <see cref="Frame.Navigate(Type, Object)"/> 的导航参数，又提供
        /// 此页在以前会话期间保留的状态的
        /// 字典。 首次访问页面时，该状态将为 null。</param>
        private async void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
        {
            // TODO:  创建适用于问题域的合适数据模型以替换示例数据
            var sampleDataGroups = await SampleDataSource.GetGroupsAsync();
            this.DefaultViewModel["Groups"] = sampleDataGroups;
        }

        /// <summary>
        /// 保留与此页关联的状态，以防挂起应用程序或
        /// 从导航缓存中放弃此页。值必须符合
        /// <see cref="SuspensionManager.SessionState"/> 的序列化要求。
        /// </summary>
        /// <param name="sender">事件的来源；通常为 <see cref="NavigationHelper"/></param>
        ///<param name="e">提供要使用可序列化状态填充的空字典
        ///的事件数据。</param>
        private void NavigationHelper_SaveState(object sender, SaveStateEventArgs e)
        {
            // TODO: 在此处保存页面的唯一状态。
        }
        #region NavigationHelper 注册

        /// <summary>
        /// 此部分中提供的方法只是用于使
        /// NavigationHelper 可响应页面的导航方法。
        /// <para>
        /// 应将页面特有的逻辑放入
        /// <see cref="NavigationHelper.LoadState"/>
        /// 和 <see cref="NavigationHelper.SaveState"/> 的事件处理程序中。
        /// 除了在早期会话期间保留的页面状态之外，
        /// LoadState 方法中还提供导航参数。
        /// </para>
        /// </summary>
        /// <param name="e">描述如何访问此页的事件数据。</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            this.navigationHelper.OnNavigatedTo(e);
            if (localSettings.Values["slider_brightness_Value"] != null)
            {
                
                Hub.Opacity = (double)localSettings.Values["slider_brightness_Value"];
                CommandBar.Opacity = (double)localSettings.Values["slider_brightness_Value"];
            }
            
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            this.navigationHelper.OnNavigatedFrom(e);
        }

        #endregion
        /// <summary>
        /// 显示在 <see cref="SectionPage"/> 中单击的组的详细信息。
        /// </summary>
        private void GroupSection_ItemClick(object sender, ItemClickEventArgs e)
        {
            var groupId = ((SampleDataGroup)e.ClickedItem).UniqueId;
            if (!Frame.Navigate(typeof(SectionPage), groupId))
            {
                //throw new Exception(this.resourceLoader.GetString("NavigationFailedExceptionMessage"));
            }
        }

        /// <summary>
        /// 显示在 <see cref="ItemPage"/> 中单击的项的详细信息。
        /// </summary>
        private void ItemView_ItemClick(object sender, ItemClickEventArgs e)
        {
            // 导航至相应的目标页，并
            // 通过将所需信息作为导航参数传入来配置新页
            var itemId = ((SampleDataItem)e.ClickedItem).UniqueId;
            if (!Frame.Navigate(typeof(ItemPage), itemId))
            {
                //throw new Exception(this.resourceLoader.GetString("NavigationFailedExceptionMessage"));
            }
        }

      private void btn_exit_Click(object sender, RoutedEventArgs e)
      {
          Application.Current.Exit();
      }
      private async void btn_rate_Click(object sender, RoutedEventArgs e)
      {;
           var uri = new Uri(String.Format("ms-windows-store:reviewapp?appid={0}", CurrentApp.AppId));
           await Windows.System.Launcher.LaunchUriAsync(uri);
      }
      private async void btn_feedback_Click(object sender, RoutedEventArgs e)
      {
          var  uri = new Uri("mailto:a15108387617@live.com?subject=彩虹游戏迷反馈");
          await Windows.System.Launcher.LaunchUriAsync(uri);
      }
      private void btn_setting_Click(object sender, RoutedEventArgs e)
      {
          this.Frame.Navigate(typeof(SettingPage));
      }

      private async  void btn_support_Click(object sender, RoutedEventArgs e)
      {
          ContentDialog_Donate contentDialog_Donate = new ContentDialog_Donate(); //ContentDialog1是系统自带的内容对话框页面
          await contentDialog_Donate.ShowAsync();
          
      }
    
        
//        #region 付费支持
//      string BuyMessage;
//      string dialog_PrimaryButton_Text;
//      string producctID = "Rainbow_Game_Fans_Donate";
//      private  void btn_support_Click(object sender, RoutedEventArgs e)
//      {
//          //var uri = new Uri(string.Format("ms-windows-store:navigate?appid={0}", "c572d421-6efd-4c19-afb5-22f19095187e"));
//          //await Windows.System.Launcher.LaunchUriAsync(uri);
//          Buy();
//     }
        
//      //async void Buy() //耐久型物品 购买
//      //{
//      //    ////var uri = new Uri(String.Format("ms-windows-store:navigate?appid={0}", "c572d421-6efd-4c19-afb5-22f19095187e"));
//      //    ////await Windows.System.Launcher.LaunchUriAsync(uri);

//      //    LicenseInformation licenseInformation = CurrentApp.LicenseInformation;
//      //    if (!licenseInformation.ProductLicenses[producctID].IsActive)
//      //    {
//      //        //rootPage.NotifyUser("Buying Product 2...", NotifyType.StatusMessage);
//      //        try
//      //        {
//      //            await CurrentApp.RequestProductPurchaseAsync(producctID);
//      //            if (licenseInformation.ProductLicenses[producctID].IsActive)
//      //            {
//      //                BuyMessage = "购买成功，谢谢支持";
//      //                dialog_PrimaryButton_Text = "确定";
//      //            }
//      //            else
//      //            {
//      //                BuyMessage = "购买失败，请重试";
//      //                dialog_PrimaryButton_Text = "重试";
//      //            }
//      //        }
//      //        catch (Exception)
//      //        {
//      //            BuyMessage = "无法购买，请重试";
//      //            dialog_PrimaryButton_Text = "重试";
//      //        } 
//      //    }
//      //    else
//      //    {
//      //        BuyMessage = "你已经购买过了，谢谢支持";
//      //        dialog_PrimaryButton_Text = "确定";
//      //    }
//      //    ShowDialog_Exit();
//      //}

//      async void Buy()//消耗型物品 购买
//      {
//          //Log("Buying Product 1...", NotifyType.StatusMessage);
//          try
//          {
//              PurchaseResults purchaseResults = await CurrentApp.RequestProductPurchaseAsync(producctID);
//              switch (purchaseResults.Status)
//              {
//                  case ProductPurchaseStatus.Succeeded:
//                      BuyMessage = "购买成功，谢谢支持";
//                      dialog_PrimaryButton_Text = "确定";

//                      //GrantFeatureLocally(producctID, purchaseResults.TransactionId);
//                      FulfillproducctID(producctID, purchaseResults.TransactionId);
//                      break;
//                  case ProductPurchaseStatus.NotFulfilled:
//                      //    if (!IsLocallyFulfilled(producctID, purchaseResults.TransactionId))
//                      //    {
//                      //        GrantFeatureLocally(producctID, purchaseResults.TransactionId);
//                      //    }
//                      BuyMessage = "购买失败，请重试";
//                      dialog_PrimaryButton_Text = "重试";
//                      FulfillproducctID(producctID, purchaseResults.TransactionId);
//                      break;
//                  case ProductPurchaseStatus.NotPurchased:
//                      //Log("Product 1 was not purchased.", NotifyType.StatusMessage);
//                      BuyMessage = "购买失败，请重试";
//                      dialog_PrimaryButton_Text = "重试";
//                      break;
//              }
//          }
//          catch (Exception)
//          {
//              //Log("Unable to buy Product 1.", NotifyType.ErrorMessage);
//              BuyMessage = "无法购买，请重试";
//              dialog_PrimaryButton_Text = "重试";
//          }
//          ShowDialog_Exit();
//      }
//      private async void FulfillproducctID(string productId, Guid transactionId)  //消耗掉物品，以便再次购买
//      {
//          try
//          {
//              FulfillmentResult result = await CurrentApp.ReportConsumableFulfillmentAsync(productId, transactionId);
//              //switch (result)
//              //{
//              //    case FulfillmentResult.Succeeded:
//              //        //Log("You bought and fulfilled product 1.", NotifyType.StatusMessage);

//              //        break;
//              //    case FulfillmentResult.NothingToFulfill:
//              //        Log("There is no purchased product 1 to fulfill.", NotifyType.StatusMessage);
//              //        break;
//              //    case FulfillmentResult.PurchasePending:
//              //        Log("You bought product 1. The purchase is pending so we cannot fulfill the product.", NotifyType.StatusMessage);
//              //        break;
//              //    case FulfillmentResult.PurchaseReverted:
//              //        Log("You bought product 1. But your purchase has been reverted.", NotifyType.StatusMessage);
//              //        // Since the user's purchase was revoked, they got their money back.
//              //        // You may want to revoke the user's access to the consumable content that was granted.
//              //        break;
//              //    case FulfillmentResult.ServerError:
//              //        Log("You bought product 1. There was an error when fulfilling.", NotifyType.StatusMessage);
//              //        break;
//              //}
//          }
//          catch (Exception)
//          {
//              //Log("You bought Product 1. There was an error when fulfilling.", NotifyType.ErrorMessage);
//          }
//          //ShowDialog_Exit();
//      }
//      async void ShowDialog_Exit()
//      {

//          ContentDialog dialog = new ContentDialog()
//          {
//              Title = "购买确认", //标题
//              Content = BuyMessage,//内容
//              FullSizeDesired = false,  //是否全屏展示
//              PrimaryButtonText = dialog_PrimaryButton_Text,//第一个按钮内容
//              SecondaryButtonText = "取消"
//          };
//          dialog.Background = new SolidColorBrush(Colors.Red);
//          if (localSettings.Values["slider_brightness_Value"] != null)
//          {
//              dialog.Opacity = (double)localSettings.Values["slider_brightness_Value"];
//          }
//          dialog.SecondaryButtonClick += dialog_SecondaryButtonClick;//第二个按钮单击事件
//          dialog.PrimaryButtonClick += dialog_PrimaryButtonClick;

//          ContentDialogResult result = await dialog.ShowAsync();
//          if (result == ContentDialogResult.Primary) { } //处理第一个按钮的返回
//          else if (result == ContentDialogResult.Secondary) { }//处理第二个按钮的返回

//      }
//      void dialog_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args)
//      {
//          //await new MessageDialog("您选择了第一个按钮").ShowAsync();
//          if (dialog_PrimaryButton_Text == "重试")
//              Buy();
//          //else
//          //    this.navigationHelper.GoBack();
//      }
//      void dialog_SecondaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args)
//      {
//          //await new MessageDialog("您选择了第二个按钮").ShowAsync();
//      }
//#endregion

     
     

    }
}
